package com.xhai.admin.service;

import com.xhai.common.utils.classes.CollectionUtils;
import com.xhai.domain.entity.SysPerm;
import com.xhai.domain.entity.SysRole;
import com.xhai.service.SysPermService;
import com.xhai.service.SysResourceService;
import com.xhai.service.SysRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xhai
 * @description 权限处理
 * @date 2025/6/9
 */
@Component
public class PermissionService {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysPermService sysPermService;

    @Resource
    private SysResourceService sysResourceService;


    /**
     * 根据岗位ids获取权限集合
     *
     * @param postIds
     * @return
     */
    public Set<String> getPermissionByPostIds(Set<Long> postIds) {
        Set<String> permissions = new HashSet<>();

        if (CollectionUtils.isEmpty(postIds)) {
            return permissions;
        }
        // 获取角色
        List<SysRole> roles = sysRoleService.selectRoleByPostIds(postIds);

        if (CollectionUtils.isEmpty(roles)) {
            return permissions;
        }
        // 获取权限
        List<SysPerm> perms = sysPermService.selectPermByRoleIds(roles.stream().map(SysRole::getRoleId).collect(Collectors.toSet()));
        if (CollectionUtils.isEmpty(perms)) {
            return permissions;
        }
        permissions = perms.stream().map(SysPerm::getPermCode).collect(Collectors.toSet());

        return permissions;
    }
}
